package com.mlnx.push.websocket.server.handler;

import com.mlnx.mptp.ResponseCode;
import com.mlnx.mptp.push.PushPacket;
import com.mlnx.push.config.PushConfig;
import com.mlnx.push.websocket.server.session.WebsocketPushNettySession;
import com.mlnx.push.websocket.server.protocol.RegisterMessage;
import com.mlnx.tp.base.model.DeviceType;

import org.shan.mq.session.core.Session;

import java.util.Date;

import io.netty.channel.ChannelHandlerContext;

/**
 * Created by amanda.shan on 2019/10/31.
 */
public class RegisterHandle extends BaseSimpleChannelInboundHandler<RegisterMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RegisterMessage registerMessage) throws Exception {

        DeviceType deviceType = registerMessage.getDeviceType();

        switch (deviceType) {
            case USR:

                WebsocketPushNettySession pushNettySession = new WebsocketPushNettySession();
                pushNettySession.setUsername(registerMessage.getUsrName());
                pushNettySession.setClientId(registerMessage.getUsrName());
                pushNettySession.setPassword(registerMessage.getPassword());

                if (registerMessage.getKeepAliveTimer() != null) {
                    pushNettySession.setKeepAliveSeconds(registerMessage.getKeepAliveTimer());
                }else{
                    pushNettySession.setKeepAliveSeconds(PushConfig.PUSH_PROPERTIES.getDefaultReciveTimeoutSecond());
                }

                log.info("用户:" + registerMessage.getUsrName() + " 注册:" + ctx.channel().toString());

                Session session = getSessionManager().getSession(ctx.channel());
                if (session != null) {
                    // 收到重复注册包
                    log.info("同一个channel重复收到注册包");
                } else {
                    // 新用户注册
                    pushNettySession.setChannel(ctx.channel());
                    pushNettySession.setLastPacketTime(new Date());
                    getSessionManager().addSession(pushNettySession);
                }

                PushPacket packet = new PushPacket().registerAck(registerMessage.getDeviceType(), ResponseCode.SUCESS);
                ctx.channel().writeAndFlush(packet);

                break;
            default:
                log.error("非法用户类型注册到push服务中:{}", deviceType);
        }
    }
}
